package com.geek.bucks.service;

import com.geek.bucks.entity.Coffee;
import com.geek.bucks.entity.CoffeeOrder;
import com.geek.bucks.entity.OrderState;
import com.geek.bucks.repository.CoffeeOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class CoffeeOrderService {
    @Autowired
    private CoffeeOrderRepository coffeeOrderRepository;

    public CoffeeOrder get(Long id){
        return coffeeOrderRepository.getOne(id);
    }

    public CoffeeOrder createOrder(String customer, List<Coffee> coffees) {
        CoffeeOrder save = coffeeOrderRepository.save(
                CoffeeOrder.builder()
                        .customer(customer)
                        .items(coffees)
                        .state(OrderState.INIT)
                        .build());
        log.info("new order：{}", save);
        return save;
    }

    public Boolean updateState(CoffeeOrder coffeeOrder, OrderState orderState) {
        if (orderState.compareTo(coffeeOrder.getState()) <= 0) {
            log.warn("wrong state order: {}, {}", orderState, coffeeOrder.getState());
            return false;
        } else {
            coffeeOrder.setState(orderState);
            coffeeOrderRepository.save(coffeeOrder);
            log.info("updated order: {}", coffeeOrder);
            return true;
        }
    }
}
